package com.tanzeer.deliverytracker.fragments;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.tanzeer.deliverytracker.R;
import com.tanzeer.deliverytracker.utility.ApplicationVars;

public class Fragment_webview extends Fragment {

	private EditText mEditText;
	private Button mSearchButton;
	private Button mNewSearchButton;
	private LinearLayout mTableLinearLayout;
	private TableLayout mItemSummaryTable;
	private LinearLayout mErrorLayout;
	private TextView mErrorTextView;
	private LinearLayout mActivityErrorLayout;
	private TextView mActivityErrorTextView;
	private TableLayout mActivitySummaryTable;
	private TableRow mItemTableRow;
	private ProgressBar mProgressBar;
	private LinearLayout mProgressBarLayout;
	private ArrayList<TableRow> list;
	private Button mNewSearchButtonError;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_webview, null, false);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mEditText = (EditText) view.findViewById(R.id.editText1);
		mSearchButton = (Button) view.findViewById(R.id.button1);
		mNewSearchButton = (Button) view.findViewById(R.id.buttonnewsearch);
		mNewSearchButtonError = (Button) view.findViewById(R.id.buttonnewsearchinerror);
		mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar2);
		mErrorLayout = (LinearLayout)view.findViewById(R.id.errorTxtLayout);
		mErrorTextView = (TextView)view.findViewById(R.id.textView003);
		mActivityErrorLayout = (LinearLayout)view.findViewById(R.id.errorTxtLayoutActivityInfo);
		mActivityErrorTextView = (TextView)view.findViewById(R.id.textView007);
		mProgressBarLayout = (LinearLayout) view
				.findViewById(R.id.progressBarLayout);
		mTableLinearLayout = (LinearLayout) view
				.findViewById(R.id.tableskeeper);
		mItemSummaryTable = (TableLayout) view
				.findViewById(R.id.itemsummarytable);
		mActivitySummaryTable = (TableLayout) view
				.findViewById(R.id.activitysummary);
		mSearchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mActivityErrorLayout.setVisibility(View.GONE);
				mErrorLayout.setVisibility(View.GONE);
				mErrorTextView.setVisibility(View.GONE);
				mTableLinearLayout.setVisibility(View.GONE);
				if (mEditText.getText().length() != 0) {
					startProcess();
				}
			}
		});
		mNewSearchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mActivityErrorLayout.setVisibility(View.GONE);
				mEditText.setText("");
				mTableLinearLayout.setVisibility(View.GONE);
				mErrorLayout.setVisibility(View.GONE);
				mErrorTextView.setVisibility(View.GONE);
				mEditText.requestFocus();

			}
		});
		mNewSearchButtonError.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mActivityErrorLayout.setVisibility(View.GONE);
				mEditText.setText("");
				mTableLinearLayout.setVisibility(View.GONE);
				mErrorLayout.setVisibility(View.GONE);
				mErrorTextView.setVisibility(View.GONE);
				mEditText.requestFocus();

			}
		});

	}

	private void startProcess() {
		if (ApplicationVars.getInstance().isNetworkAvailable(getActivity())) {
			refreshData();
			mProgressBarLayout.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.VISIBLE);
			if (validateDataForTrackingNo(mEditText.getText().toString())) {
				new SendTask(getActivity()).execute();
			} else {
				Toast.makeText(getActivity(), R.string.valid_trackno_needed,
						Toast.LENGTH_SHORT).show();
				mProgressBarLayout.setVisibility(View.GONE);
				mProgressBar.setVisibility(View.GONE);
				mEditText.setText("");
				mTableLinearLayout.setVisibility(View.GONE);
				mEditText.requestFocus();
			}
		} else {
			Toast.makeText(getActivity(), R.string.network_not_available,
					Toast.LENGTH_SHORT).show();
		}

	}

	private void refreshData() {
		if (mItemTableRow != null) {
			mItemTableRow.removeAllViews();
		}
		if (list != null && list.size() != 0) {
			for (TableRow trow : list) {
				trow.removeAllViews();
			}
		}
	}

	private boolean validateDataForTrackingNo(String stringToCheck) {
		boolean res = false;
		if (stringToCheck != null && !stringToCheck.equals("")) {
			for (int i = 0; i < stringToCheck.length(); i++) {
				if (Character.isLetter(stringToCheck.charAt(i))
						|| Character.isDigit(stringToCheck.charAt(i))) {
					res = true;
				} else {
					res = false;
					break;
				}
			}
		} else {
			res = false;
		}
		return res;
	}

	public class SendTask extends AsyncTask<Void, Void, String> {

		private Context mContext;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		public SendTask(Context context) {
			this.mContext = context;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {

				String searchEditBoxValue = "";

				HttpClient http = new DefaultHttpClient();

				if (mEditText != null) {
					if (mEditText.getText().toString().equals("ok")) {

						searchEditBoxValue = "";
					}
					searchEditBoxValue = mEditText.getText().toString();
				}

				HttpGet get = new HttpGet(
						"http://globaltracktrace.ptc.post/gtt.web/Search.aspx?__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKMTc3NjQ4MjIxM2Rke75CFXa4GKxBOHumSyRDu081aGM%3D&__EVENTVALIDATION=%2FwEWAwKyj9zfDgKj5vrWDAKln%2FPuCgvWD%2FM%2FMsU5fSmm%2F1vVYpTAdczC&txtItemID="
								+ searchEditBoxValue + "&btnSearch=Search");

				HttpResponse response = http.execute(get);
				String responseStr = new BasicResponseHandler()
						.handleResponse(response); // Basic handler

				return responseStr;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				return null;

			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(String str) {

			mProgressBarLayout.setVisibility(View.GONE);
			mProgressBar.setVisibility(View.GONE);
			if (str != null && !str.contains("Item Summary")) {
				LayoutInflater li = (LayoutInflater) getActivity()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				mItemTableRow = (TableRow) li.inflate(R.layout.table_row, null);

				TextView one = (TextView) mItemTableRow
						.findViewById(R.id.textview1);
				one.setTextSize(10);
				TextView two = (TextView) mItemTableRow
						.findViewById(R.id.textview2);
				two.setTextSize(10);
				TextView three = (TextView) mItemTableRow
						.findViewById(R.id.textview3);
				three.setTextSize(10);
				TextView four = (TextView) mItemTableRow
						.findViewById(R.id.textview4);
				four.setTextSize(10);
				parseHtmlForItemSummary(str, one, two, three, four);

				mTableLinearLayout.setVisibility(View.VISIBLE);
				mItemSummaryTable.addView(mItemTableRow);

				int count = countRowsForActivitySummary(str);
				list = new ArrayList<TableRow>();
				
				for (int i = 0; i < count; i++) {
					String returnedRowData = parseHtmlForRow(str, i);
					feedListwithRow(mContext, returnedRowData, list);
				}
				
                if (count == 0) {
                	String returnedRowData = parseHtmlForInfoInActivityTable(str);
                	mActivityErrorLayout.setVisibility(View.VISIBLE);
            		mActivityErrorTextView.setText(returnedRowData); 
                }

				for (TableRow trow : list) {
					mActivitySummaryTable.addView(trow);
				}
			} else {
				if (str != null) {
					mErrorLayout.setVisibility(View.VISIBLE);
					mErrorTextView.setVisibility(View.VISIBLE);
					String errorResponseData = parseHtmlForServerErrorResponse(str);
					mErrorTextView.setText(errorResponseData);
				}
			}

		}
		
		private String parseHtmlForInfoInActivityTable(String str) {
			int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
			str = str.substring(resultsPanelDivStart);
			resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
					+ "<div id=\"resultsPanel\">".length(); // refreshing values
			int resultsPanelDivEnd = str.indexOf("</div>");
			str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
			str = skipTag(str, "<table>", "</table>");
			str = skipTag(str, "<table>", "</table>");
			str = extractString(str, "<p>", "</p>");	
			return str;
		}

		private String parseHtmlForServerErrorResponse(String str) {
			int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
			str = str.substring(resultsPanelDivStart);
			resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
					+ "<div id=\"resultsPanel\">".length(); // refreshing values
			int resultsPanelDivEnd = str.indexOf("</div>");
			str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
			str = extractString(str, "<p>", "</p>");
			return str;
		}

		private String parseHtmlForRow(String str, int rowNotoExtract) {

			int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
			str = str.substring(resultsPanelDivStart);
			resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
					+ "<div id=\"resultsPanel\">".length(); // refreshing values
			int resultsPanelDivEnd = str.indexOf("</div>");
			str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
			str = skipTag(str, "<table>", "</table>");
			str = extractString(str, "<table>", "</table>");
			str = skipTag(str, "<tr>", "</tr>"); // skip heading
			if (rowNotoExtract == 0) {
				str = extractString(str, "<tr>", "</tr>");
			}
			if (rowNotoExtract == 1) {
				str = skipTag(str, "<tr>", "</tr>");
				str = extractString(str, "<tr>", "</tr>");
			} else if (rowNotoExtract == 2) {
				str = skipTag(str, "<tr>", "</tr>");
				str = skipTag(str, "<tr>", "</tr>");
				str = extractString(str, "<tr>", "</tr>");
			} else if (rowNotoExtract == 3) {
				str = skipTag(str, "<tr>", "</tr>");
				str = skipTag(str, "<tr>", "</tr>");
				str = skipTag(str, "<tr>", "</tr>");
				str = extractString(str, "<tr>", "</tr>");
			}

			return str;

		}

		private void feedListwithRow(Context context, String str,
				ArrayList<TableRow> list) {
			String dataOne = extractString(str, "<td>", "</td>");
			TableRow tr = null;
			LayoutInflater li = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			tr = (TableRow) li.inflate(R.layout.table_row, null);

			TextView tv = (TextView) tr.findViewById(R.id.textview1);
			String[] dataOneArr = dataOne.split(" ");
			String[] timeArr = null;
			timeArr = dataOneArr[1].split(":");
			if (dataOneArr[2].equals("PM")) {
				timeArr[0] = "" + (Integer.parseInt(timeArr[0]) + 12);
				dataOneArr[1] = timeArr[0] + ":" + timeArr[1];
			} else {
				if (timeArr[0].length() < 2) {
					timeArr[0] = '0' + timeArr[0];
				}
				dataOneArr[1] = timeArr[0] + ":" + timeArr[1];
			}

			final String OLD_FORMAT = "MM/dd/yyyy";
			final String NEW_FORMAT = "dd.MM.yyyy";

			// August 12, 2010
			String oldDateString = dataOneArr[0];
			String newDateString = null;

			SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
			Date d = null;
			try {
				d = sdf.parse(oldDateString);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sdf.applyPattern(NEW_FORMAT);
			newDateString = sdf.format(d);

			tv.setText(newDateString + " " + dataOneArr[1]);

			str = skipTag(str, "<td>", "</td>");

			String dataTwo = extractString(str, "<td>", "</td>");

			tv = (TextView) tr.findViewById(R.id.textview2);
			tv.setText(dataTwo);
			str = skipTag(str, "<td>", "</td>");

			String dataThree = extractString(str, "<td>", "</td>");
			tv = (TextView) tr.findViewById(R.id.textview3);
			tv.setText(dataThree);
			str = skipTag(str, "<td>", "</td>");

			String dataFour = extractString(str, "<td>", "</td>");
			tv = (TextView) tr.findViewById(R.id.textview4);
			tv.setText(dataFour);

			
			
			
			
			
			list.add(tr);
		}
		
		

		private void parseHtmlForItemSummary(String str, TextView one,
				TextView two, TextView three, TextView four) {
			int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
			str = str.substring(resultsPanelDivStart);
			resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
					+ "<div id=\"resultsPanel\">".length(); // refreshing values
			int resultsPanelDivEnd = str.indexOf("</div>");
			str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
			str = extractString(str, "<table>", "</table>");
			str = skipTag(str, "<tr>", "</tr>");
			String trackingNo = extractString(str, "<td>", "</td>");
			one.setText(trackingNo);
			str = skipTag(str, "<td>", "</td>");
			String origin = extractString(str, "<td>", "</td>");
			two.setText(origin);
			str = skipTag(str, "<td>", "</td>");
			String dest = extractString(str, "<td>", "</td>");
			three.setText(dest);
			str = skipTag(str, "<td>", "</td>");
			String status = extractString(str, "<td>","</td>");

			if (status.equalsIgnoreCase("Delivered")) {
				four.setBackgroundColor(Color.parseColor("#80FF80"));
			}else if (status.equalsIgnoreCase("On route")) {
				four.setBackgroundColor(Color.parseColor("#FFFF00"));
			}

			four.setText(status);
		}

		private int countRowsForActivitySummary(String str) {
			int res = 0;
			int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
			str = str.substring(resultsPanelDivStart);
			resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
					+ "<div id=\"resultsPanel\">".length(); // refreshing values
			int resultsPanelDivEnd = str.indexOf("</div>");
			str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
			str = skipTag(str, "<table>", "</table>");
			str = extractString(str, "<table>", "</table>");
			str = skipTag(str, "<tr>", "</tr>"); // first heading row is skipped
			while ((str = skipTag(str, "<tr>", "</tr>")) != null) {
				res++;
			}
			return res;
		}

		public String extractString(String hayStack, String startTag,
				String endTag) {
			String extractedString = null;
			try {
			int indexEndTagStart = hayStack.indexOf(endTag);
			startTag = startTag.substring(0, startTag.lastIndexOf(">"));
			int indexStartTagStart = hayStack.indexOf(startTag);

			int indexStartTagEnd = hayStack.indexOf('>', indexStartTagStart);
			indexStartTagEnd++;
			extractedString = hayStack.substring(indexStartTagEnd,
					indexEndTagStart);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return extractedString;
		}

		public String skipTag(String hayStack, String startTag, String endTag) {
			String resultant = null;
			try {
				int endIndex = hayStack.indexOf(endTag);
				resultant = hayStack.substring(endIndex + endTag.length());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resultant;
		}
	}

}
